<script setup>
// 增加onMounted导入
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { HomeFilled } from "@element-plus/icons-vue"
import { useRouter } from "vue-router"
import axios from 'axios'
import { getSelectedCourses, getCourses, selectCourse, deselectCourse, createCourseProgress } from '@/api/student/student_course_select'


const router = useRouter()
const backToHome = () => {
    router.push('/student/Homepage/PersonalHomepage')
}

const getStuId = () => {
  try {
    const rawInfo = localStorage.getItem('studentUserInfo')
    if (!rawInfo) throw new Error('无登录信息')

    const userInfo = JSON.parse(rawInfo)
    if (!userInfo?.stu_id) {
      localStorage.removeItem('studentUserInfo')
      router.push('/student/login')
      return null
    }
    return userInfo.stu_id
  } catch (e) {
    console.error('学生ID获取失败:', e)
    return null
  }
}

defineExpose({
  getStuId
})

// 替换原有模拟数据
const courses = ref([])
const selectedCourseIds = ref(new Set())

// 获取当前登录用户名
const getCurrentUsername = () => {
  const studentUserInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}')
  return studentUserInfo.username || studentUserInfo.stu_id || null
}

// 获取所有课程
const fetchCourses = async () => {
  try {
    console.log('正在获取课程数据...')
    const response = await getCourses()
    console.log('课程数据响应:', response)

    // 如果响应是数组，直接使用
    if (Array.isArray(response)) {
      courses.value = response
    }
    // 如果响应是对象，可能包含在data字段中
    else if (response && Array.isArray(response.data)) {
      courses.value = response.data
    }
    // 如果是其他格式，尝试转换
    else if (response) {
      courses.value = response
    }

    console.log('获取到课程数据:', courses.value)
  } catch (error) {
    console.error('课程加载失败:', error)
    ElMessage.error('课程加载失败: ' + (error.message || '未知错误'))
  }
}

// 获取已选课程
const fetchSelectedCourses = async () => {
  try {
    console.log('正在获取已选课程数据...')

    // 清空当前选课状态
    selectedCourseIds.value = new Set()

    // 获取当前登录用户
    const username = getCurrentUsername()
    if (!username) {
      console.warn('未找到登录用户信息，无法获取选课状态')
      return
    }

    console.log('当前用户:', username)

    // 从服务器获取最新状态
    const response = await getSelectedCourses({ params: { username } })
    console.log('已选课程响应:', response)

    // 确保data是数组格式
    let selectedIds = []
    if (Array.isArray(response)) {
      selectedIds = response
    } else if (Array.isArray(response.data)) {
      selectedIds = response.data
    } else if (response.data && Array.isArray(response.data.data)) {
      selectedIds = response.data.data
    }

    // 确保所有课程ID都是数字类型
    selectedIds = selectedIds.map(id => Number(id))

    // 只使用服务器返回的数据，不再与本地缓存合并
    if (selectedIds.length > 0) {
      console.log('从服务器获取到已选课程:', selectedIds)
      selectedCourseIds.value = new Set(selectedIds)
    }

    console.log('最终的已选课程:', Array.from(selectedCourseIds.value))
  } catch (error) {
    console.error('已选课程加载失败:', error)
    ElMessage.error('已选课程加载失败: ' + (error.message || '未知错误'))
  }
}

// 默认当前页
const currentPage = ref(1);
//每页选项数目
const pageSize = ref(6);

// 已选课程
const selectedCourses = ref([]);

// 计算分页后的课程
const paginatedCourses = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return courses.value.slice(start, end);
});

// 判断课程是否已选择的计算属性
const isCourseSelected = (courseId) => {
    return selectedCourseIds.value.has(Number(courseId));
};

// 查看详情
const viewDetail = (courseId) => {
    router.push({ path: '/courseDetail', query: { id: courseId } });
};

// 切换选择状态
const toggleSelection = async (courseId) => {
  try {
    // 获取当前登录用户
    const username = getCurrentUsername()
    if (!username) {
      ElMessage.error('请先登录')
      return
    }

    // 确保课程ID是数字类型
    courseId = Number(courseId)
    console.log('切换课程选择状态 - 开始:', courseId)
    console.log('当前已选课程:', Array.from(selectedCourseIds.value))

    let success = false

    if (selectedCourseIds.value.has(courseId)) {
      console.log('执行取消选课操作...')
      const response = await deselectCourse(courseId, username)
      console.log('取消选课响应:', response)

      // 检查API是否成功
      if (response && (response.status === 'deleted' || response.status === 200)) {
        success = true
        selectedCourseIds.value.delete(courseId)
        console.log('成功取消选课:', courseId)
      } else {
        ElMessage.error('取消选课失败，请重试')
      }
    } else {
      console.log('执行选择课程操作...')
      const response = await selectCourse(courseId, username)
      console.log('选课响应:', response)

      // 检查API是否成功
      if (response && (response.status === 'success' || response.status === 200)) {
        success = true
        selectedCourseIds.value.add(courseId)
        console.log('成功选课:', courseId)

        // 选课成功后，创建学习进度记录
        console.log('正在创建课程进度记录...')
        try {
          const progressResponse = await createCourseProgress(courseId, username)
          console.log('创建课程进度记录响应:', progressResponse)
          if (progressResponse && progressResponse.status === 'error') {
            console.warn('创建课程进度记录失败，但不影响选课:', progressResponse.message)
          }
        } catch (progressError) {
          console.warn('创建课程进度记录时出错，但不影响选课:', progressError)
        }
      } else {
        ElMessage.error('选课失败，请重试')
      }
    }

    if (success) {
      console.log('选课状态变更后的已选课程:', Array.from(selectedCourseIds.value))
    }

    // 无论成功与否，都从服务器获取最新状态来确保界面一致
    setTimeout(async () => {
      console.log('刷新选课状态...')
      await fetchSelectedCourses()
    }, 1000)
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败: ' + (error.message || '未知错误'))
  }
}

// 分页变化
const handlePageChange = (newPage) => {
    currentPage.value = newPage;
};

// 页面加载时获取数据
onMounted(async () => {
  console.log('组件已挂载，开始获取数据...')
  try {
    // 先获取所有课程信息
    await fetchCourses()

    // 然后获取当前用户的已选课程信息
    await fetchSelectedCourses()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
})

// 切换聊天窗口显示/隐藏
const toggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

</script>

<template>
    <el-container class="course-select-container">
        <el-header class="course-header">
            <el-row>
                <el-col :span="2">
                    <el-icon size="30" color="#409EFF">
                        <HomeFilled @click="backToHome"/>
                    </el-icon>
                </el-col>
                <el-col :span="20">
                    <div class="page-title">
                        课程选择
                    </div>
                </el-col>
                <el-col :span="2">

                </el-col>
            </el-row>
        </el-header>
        <el-main class="course-main">
            <div class="course-list">
                <el-card
                    v-for="course in paginatedCourses"
                    :key="course.id"
                    class="course-card"
                    shadow="hover"
                >
                    <div class="course-content">
                        <h3>{{ course.name }}</h3>
                        <p>{{ course.description }}</p>
                        <div class="course-actions">
                            <el-button
                                type="primary"
                                size="small"
                                @click="viewDetail(course.id)"
                            >
                                查看详情
                            </el-button>
                            <el-button
                                :type="isCourseSelected(course.id) ? 'success' : 'primary'"
                                size="small"
                                @click="toggleSelection(course.id)"
                            >
                                {{ isCourseSelected(course.id) ? '已选择' : '选择课程' }}
                            </el-button>
                        </div>
                    </div>
                </el-card>
            </div>
        </el-main>
        <el-footer class="course-footer">
            <el-pagination
                v-model="currentPage"
                :page-size="pageSize"
                :total="courses.length"
                :background="true"
                layout="prev, pager, next, jumper"
                @current-change="handlePageChange"
            />
        </el-footer>
    </el-container>
<!--    <div class="chat-bubble" @click="toggleChat">-->
<!--        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z'/%3E%3C/svg%3E" alt="聊天">-->
<!--    </div>-->

<!--    <div class="chat-container" id="chatContainer">-->
<!--        <iframe src="http://121.40.242.43/chatbot/W6TLrJcFFhFE1Zpi" class="chat-iframe"></iframe>-->
<!--    </div>-->
</template>

<style scoped>
.course-select-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  overflow: hidden;
}

.course-header {
  padding: 10px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0,0,0,0.1);
  flex: 0 0 auto;
}

.page-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.course-main {
  padding: 15px;
  flex: 1;
  overflow-y: auto;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

.course-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.course-card {
  width: 100%;
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
  border-left: 4px solid #409EFF;
}

.course-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.course-content {
  display: flex;
  flex-direction: column;
  padding: 10px 15px;
}

.course-content h3 {
  margin-top: 0;
  margin-bottom: 8px;
  color: #303133;
  font-size: 16px;
}

.course-content p {
  margin-bottom: 10px;
  color: #606266;
  line-height: 1.4;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.course-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.course-footer {
  height: auto;
  padding: 10px 0;
  display: flex;
  justify-content: center;
  background-color: #fff;
  flex: 0 0 auto;
  box-shadow: 0 -1px 4px rgba(0,0,0,0.05);
}
.chat-bubble {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 60px;
    height: 60px;
    background-color: #007bff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 1000;
}

.chat-bubble img {
    width: 30px;
    height: 30px;
}

.chat-container {
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 350px;
    height: 500px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    display: none;
    z-index: 999;
}

.chat-iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 10px;
}
</style>
